package util;

import html.News;

import java.sql.*;

/**
 * Created by admin on 2016/10/29 0029.
 */
public class DbUtil {
    private static final String userName = "root";
    private static final String userPwd = "123456";
    private static final String url = "jdbc:mysql://localhost:3306/news?user=" + userName + "&password=" + userPwd + "&userUnicode=true&characterEncoding=utf-8";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getDbConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url);
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                throw new Exception("连接数据库失败");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return conn;
    }

    public static String queryByTitle(String title){
        Connection connection = DbUtil.getDbConnection();
        if (connection == null) return null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement("select *from news where title = ?");
            preparedStatement.setString(1, title);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next())
            {
                return resultSet.getString(1);
            }else{
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.closeDB(connection, preparedStatement, resultSet);
        }
        return null;

    }
    public static boolean addNews(News news) {
        Connection connection = DbUtil.getDbConnection();
        if (connection == null) return false;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement("insert into news(title,url,long_time) values(?,?,?)");
            preparedStatement.setString(1, news.getTitle());
            preparedStatement.setString(2, news.getUrl());
            preparedStatement.setLong(3, news.getLongTime());
            int rowCount = preparedStatement.executeUpdate();
            if (rowCount != 0) return true;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.closeDB(connection, preparedStatement, resultSet);
        }
        return false;
    }

    public static void closeDB(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (ps != null) ps.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
